package com.njupt.sellsec.handler;

import com.alibaba.fastjson.JSON;
import com.njupt.sellsec.access.AccessLimit;
import com.njupt.sellsec.domain.SellUser;
import com.njupt.sellsec.redis.AccseeKey;
import com.njupt.sellsec.redis.RedisService;
import com.njupt.sellsec.redis.SecSellKey;
import com.njupt.sellsec.result.CodeMsg;
import com.njupt.sellsec.result.Result;
import com.njupt.sellsec.service.Impl.SellUserServiceImpl;
import com.njupt.sellsec.service.SellUserService;
import com.njupt.sellsec.util.CookieUtil;
import com.sun.tools.corba.se.idl.StringGen;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 17:14 2018/8/2
 * @Modified By:
 **/
@Service
@Slf4j
public class AccessInterceper extends HandlerInterceptorAdapter {
    @Autowired
    private SellUserService sellUserService;
    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       if (handler instanceof HandlerMethod){

           SellUser user = getSellUser(request,response);
           UserContext.setUser(user);

           HandlerMethod method = (HandlerMethod) handler;
           //获取注解方法的类
           AccessLimit limit =method.getMethodAnnotation(AccessLimit.class);
           if (limit==null){
               return true;
           }


           int maxCount = limit.maxCount();
           int seconds = limit.seconds();
           boolean needLogin = limit.needLogin();
           String key = request.getRequestURI();
           if (needLogin){
               if (user==null){
                   render(response, CodeMsg.SERVER_ERROR);
               }
           }

           key+="_"+user.getId();
           log.info("【访问控制进来了-------------】");
           Integer count = redisService.get(AccseeKey.AccessController(seconds),key,Integer.class);
           log.info("【从缓存中拿到的count为：】,count={}",count);
           if (count==null){
               redisService.set(AccseeKey.AccessController(seconds),key,1);
           }else if (count<5){
               redisService.incr(AccseeKey.AccessController(seconds),key);
           }else {
               render(response,CodeMsg.QEQUEST_LIMITED_REPEAUED);
           }

       }
        return true;
    }

    private void render(HttpServletResponse response, CodeMsg serverError) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        String str = JSON.toJSONString(Result.error(serverError));
        out.write(str.getBytes("UTF-8"));
        out.flush();
        out.close();
    }

    private SellUser getSellUser(HttpServletRequest request,
                                 HttpServletResponse response){
        String paramToken = request.getParameter(SellUserServiceImpl.COOKIE_NAME_TOKEN);
        //Cookie cookie = CookieUtil.getCookie(request,SellUserServiceImpl.COOKIE_NAME_TOKEN);

        //String cookieToken = cookie.getName();
        String cookieToken = getCookieValue(request,SellUserServiceImpl.COOKIE_NAME_TOKEN);
        if (StringUtils.isEmpty(cookieToken)&&StringUtils.isEmpty(paramToken)){
            return null;
        }
        String token = StringUtils.isEmpty(paramToken)?cookieToken:paramToken;
        return sellUserService.findUserByToken(response,token);
    }

    private String getCookieValue(HttpServletRequest request, String cookiName) {
        Cookie[]  cookies = request.getCookies();
        if(cookies == null || cookies.length <= 0){
            return null;
        }
        for(Cookie cookie : cookies) {
            if(cookie.getName().equals(cookiName)) {
                return cookie.getValue();
            }
        }
        return null;
    }
}
